export class IndexedDB {
  db: IDBOpenDBRequest;
  tableName: string;
  connection: IDBDatabase;
  store: IDBObjectStore;
  constructor() {
    this.tableName = 'user';
    this.connection = null as any;
    this.db = null as any;
    this.store = null as any;
    this.createIndexedDb();
  }

  createIndexedDb() {
    const self = this;
    this.db = window.indexedDB.open('myDatabase');
    this.db.onupgradeneeded = function (event: IDBVersionChangeEvent) {
      const { result } = event?.target as IDBOpenDBRequest;
      self.connection = result;
      if (!self.connection.objectStoreNames.contains(self.tableName)) {
        self.createUserTable();
      }

      // backupUserTable();
    };

    // 下次打开数据库时触发
    this.db.onsuccess = function (event: Event) {
      console.log('===========>onsuccess', event);
      const { result } = event?.target as IDBOpenDBRequest;
      self.connection = result;
      self.backupUserTable();
    };
    this.db.onerror = function () {};
  }

  // 回滚数据
  restoreUserTable() {
    this.createTransaction();
    const store = this.store;
    const backup = JSON.parse(localStorage.getItem('backupData') || '{}');
    Object.keys(backup).forEach((key) => {
      store.put(backup[key]);
    });
    localStorage.removeItem('backupData');
  }

  // 备份用户表
  backupUserTable() {
    const transaction = this.connection.transaction(this.tableName, 'readonly');
    const store = transaction.objectStore(this.tableName);
    const data: Record<string, any> = {};
    store.openCursor().onsuccess = function (event) {
      const { result: cursor } = event.target as IDBRequest;
      if (cursor) {
        data[cursor.key] = cursor.value;
        cursor.continue();
      } else {
        // 在这里 data 变量包含了所有的备份数据
        localStorage.setItem('backupData', JSON.stringify(data));
      }
    };
  }

  createUserTable() {
    this.connection.createObjectStore(this.tableName, {
      keyPath: 'user_id', // 指定主键
    });
  }

  // 创建事物
  createTransaction() {
    const tx = this.connection.transaction(this.tableName, 'readwrite');
    this.store = tx.objectStore(this.tableName);
    return this.store;
  }

  addUser(user_id: string, data?: any) {
    const self = this;
    this.createTransaction();
    const addReq = this.store.add({
      user_id: user_id || '1',
      ...(data || {}),
    });

    addReq.onsuccess = function () {
      self.backupUserTable();
    };
  }

  updateUser(content: any) {
    const self = this;
    this.createTransaction();
    const putReq = this.store.put({
      user_id: '1',
      ...content,
    });

    putReq.onsuccess = function () {
      self.backupUserTable();
    };
  }

  getUser(user_id: string) {
    return new Promise((resolve, reject) => {
      this.createTransaction();
      const getReq = this.store.get(user_id || '1');
      getReq.onsuccess = function (event: Event) {
        const { result } = event?.target as IDBOpenDBRequest;
        console.log('========>读取成功！', result);
        resolve(result);
      };

      getReq.onerror = function (error) {
        console.log('========>读取失败！', error);
        reject();
      };
    });
  }

  deleteUser(user_id: string): Promise<void> {
    {
      return new Promise((resolve, reject) => {
        this.createTransaction();
        const deleteReq = this.store.delete(user_id || '1');

        deleteReq.onsuccess = function (event) {
          // const data = event.target.result;
          console.log('========>删除成功！', event);
          resolve();
        };

        deleteReq.onerror = function () {
          reject();
        };
      });
    }
  }
}
